import axios from 'axios';
import { message } from 'antd';
import { store } from '@/redux';

const service = axios.create({
	baseURL: import.meta.env.VITE_API_URL as string,
	timeout: 30000,
	withCredentials: false,
});

service.interceptors.request.use(
	(request: any) => {
		const { headers } = request;
		const { token } = store.getState().global;
		headers['pakchoi-token'] = token;
		return request;
	},
	(err) => {
		message.error('无法发送请求');
		return Promise.reject(err.data);
	}
);

const closeLoading = () => {
	message.destroy();
};

let nologinERROR: boolean;
//拦截返回值
service.interceptors.response.use(
	(response) => {
		const {
			data: { code, data, msg },
		} = response;
		if (code !== 200) {
			if (code === 403) {
				const { pathname, origin } = window.location;
				window.location.replace(`${origin}${pathname}/#/403`);
				message.error(msg || '服务器异常');
				return Promise.reject(msg || data);
			}
			message.error(msg || '服务器异常');
			return Promise.reject(msg || data);
		}
		closeLoading();
		return Promise.resolve(data);
	},
	(err) => {
		if (!err.request) message.error('请求异常');
		else {
			const { status: code } = err.request;
			if (code == 404) message.error('未知的请求');
			else message.error('请求服务器异常');
		}
		return Promise.reject(err);
	}
);

export default service;
